<template>
  <div class="myContainer">
    <!-- 头部标题 start -->  
    <el-row>
      <el-col :span="24">
        <div class="myHeadeTitle">计划模板基本信息</div>
      </el-col>
    </el-row>
    <!-- 头部标题 end -->
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        所属小区 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-cascader
            placeholder="全部小区"
            :options="regionOptions"
            v-model="regionOptSelected"
            :disabled="disabled"
            ></el-cascader>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划模板名称 :
      </el-col>
      <el-col :span="8">
        <el-input placeholder="计划模板名称" v-model="name" :readonly="disabled"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        计划模板编号 :
      </el-col>
      <el-col :span="8">
        <el-input placeholder="计划模板编号" v-model="id" disabled></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划模板对象类型 :
      </el-col>
      <el-col :span="8">
        <template>
          <el-select v-model="modelValue" placeholder="请选择计划模板对象模型" :disabled="disabled">
            <el-option
              v-for="item in modelOptions"
              :key="item.targetname"
              :label="item.targetname"
              :value="item.targetname +'-'+item.id">
            </el-option>
          </el-select>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划模板内任务周期 :
      </el-col>
      <el-col :span="3">
        <template>
          <el-select v-model="cycleVlaue" v-if="type!='info'" placeholder="请选择周期" :readonly="disabled">
            <el-option
              v-for="item in cycleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <span v-else class="myLineHeight_40px">{{cycleVlaue | cycleListText}}</span>
        </template>
      </el-col>
      <el-col :span="1" class="myLeftMsg">
        进行 
      </el-col>
      <el-col :span="3">
        <el-input placeholder="多少次的任务" v-model="frequency" :readonly="disabled"></el-input>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划模板内任务执行期限 :
      </el-col>
      <el-col :span="3">
        <div class="myBorder">
          <input placeholder="多少天" v-model="cycle" class="myNoBorder myWidth_100px" disabled/>
          <button class="myNoBorder myWidth_35px" @click="lesCycle" :disabled="disabled"> - </button>
          <button class="myNoBorder myWidth_35px" @click="addCycle" :disabled="disabled"> + </button>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="myHeadeTitle">计划模板内任务执行项目</div>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        执行项目 :
      </el-col>
      <el-col :span="21">
        <el-button class="myBgGreen" @click="newEditDialogVisible = true" :disabled="disabled" v-if="isShow(233)"> 新 增 </el-button>
        <el-button class="myBgGreen" :disabled="disabled" v-if="subjectList.length>1 && isShow(234)" @click="onBatchDelete"> 批量删除 </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="21" :offset="3">
        <template>
          <el-table
            :data="subjectList"
            border
            @selection-change="handleSelectionChange"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="100">
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="100">
            </el-table-column>
            <el-table-column
              prop="subject_content"
              label="执行项目">
            </el-table-column>
            <el-table-column
              label="操作"
              width="100">
              <template scope="scope">
                <el-button class="look" type="text" size="small" v-if="type=='add' && isShow(235)" @click="updateSubjectList(scope.row.subject_content,scope.$index)">编辑</el-button>
                <el-button class="look" type="text" size="small" v-if="type=='update' && isShow(235)" @click="getItem(scope.row.id)">编辑</el-button> |
                <el-button class="look" type="text" size="small" @click="onDeleteSubjectItem(scope.$index,subjectList)" v-if="type=='add' && isShow(236)">删除</el-button>
                <el-button class="look" type="text" size="small" @click="onDeleteSubjectItem_update(scope.row.id)" v-if="type=='update' && isShow(236)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <div class="myHeadeTitle">计划模板状态及备注</div>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        <span class="require myVA_M">*</span>
        计划模板状态 :
      </el-col>
      <el-col :span="7" class="myLineHeight_45px">
        <template>
          <el-radio-group v-model="on" :disabled="disabled">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </template>
      </el-col>
    </el-row>
    <el-row class="myPaddingBottom_10px">
      <el-col :span="3" class="myLeftMsg">
        备注 :
      </el-col>
      <el-col :span="21">
        <el-input type="textarea" v-model="note" :readonly="disabled"></el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="20" :offset="3">
        <el-button class="myBgGreen" v-if="type=='add'" @click="onAdd">新 增</el-button>
        <el-button class="myBgGreen" v-if="type=='update' && isShow(232)" @click="onUpdate">保 存</el-button>
        <el-button class="myBgGreen" v-if="type=='add'" @click="onClose">取 消</el-button>
        <el-button class="myBgGreen"  v-if="type=='update' || type=='info'" @click="onClose">关 闭</el-button>
      </el-col>
    </el-row>


    <!--新增执行项目弹窗 start-->
    <el-dialog title="新增执行项目" class="myRoleDialog" :visible.sync="newEditDialogVisible">
      <el-row class="myPaddingTop_10px">
        <el-col :span="4" class="myLeftMsg">执行项目 :</el-col>
        <el-col :span="20">
          <el-input placeholder="填写执行项目" v-model="subjectsItem" type="textarea"></el-input>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="newEditDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='add'" @click="onAddSubject">新增</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='update'" @click="onAddUpdate">保存</el-button>
      </div>
    </el-dialog>
    <!--新增执行项目弹窗 end-->

    <!--编辑执行项目弹窗 start-->
    <el-dialog title="编辑执行项目" class="myRoleDialog" :visible.sync="editDialogVisible">
      <el-row class="myPaddingTop_10px">
        <el-col :span="4" class="myLeftMsg">执行项目 :</el-col>
        <el-col :span="20">
          <el-input placeholder="填写执行项目" v-model="editSubjectsItem" type="textarea"></el-input>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="myBgGreen" @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='update'" @click="onSubjectsItemUpdate">更 改</el-button>
        <el-button type="primary" class="myBgGreen" v-if="type=='add'" @click="onSubjectsItemUpdate_add">更 改</el-button>
      </div>
    </el-dialog>
    <!--编辑执行项目弹窗 end-->


  </div>
</template>  

<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myHeadeTitle{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
    margin-bottom:10px; 
  }
  .myHeadeTitle:before,.myHeadeTitle:after,.myBorder:before,.myBorder:after{
    content: " ";
    display: block;
    clear: both;
  }
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
  .myVA_M{
    vertical-align: middle;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top: 2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myBorder{
    border: 1px solid #bfcbd9;
    width: 182px;
    height: 40px;
  }
  .myNoBorder{
    border:none !important;
  }
  .myWidth_100px{
    width: 100px;
    float: left;
    line-height: 36px;
    padding: 0 10px;
    background: none;
  }
  .myWidth_35px{
    width: 40px;
    color: #000 !important;
    float: left;
    border-left: 1px solid #bfcbd9 !important;
    border-radius: 0 !important;
    text-align: center;
    height: 38px;
    background: none;
  }
  .el-button span{
    color: #000 !important;
  }
  .myWidth_35px:hover{
    background: #f2f2f2;
    cursor: pointer;
  }
  .myLineHeight_45px{
    line-height: 45px;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
</style>

<script>
  import { getModelDetail , GetModelObjList , cycleList , createModelManage , updateModelManage , createExecutionItem , getExecutionItemList , getExecutionItem , removeExecutionItem , updateExecutionItem} from '@/api/maintenanceplan';
  import { extractAreaIds , onSetArea } from '@/utils/misc';
  import { getRegion } from '@/utils/localstorage';
  export default {
     data(){
      return{
        modelOptions:[],
        modelValue:"",
        cycleOptions:[
          {value: '365',label: '年度任务'},
          {value: '182',label: '半年任务'},
          {value: '90',label: '季度任务'},
          {value: '30',label: '月度任务'},
          {value: '1',label: '日常巡检'}
        ],
        cycleVlaue:"",
        cycle:"",
        modelId:"",
        detail:[],
        on:1,
        newEditDialogVisible:false,
        type:"",
        disabled:true,
        frequency:"",
        subjectList:[],//缓存的执行项目
        subjectsItem:"",
        subjectsCacheList:[],
        cycleList:cycleList,
        name:"",
        id:"",
        note:"",
        editDialogVisible:false,
        editSubjectsItem:"",
        idArr:[],
        subject_id:"",
        add_subItem:"",
        s_id:"",
        regionOptions: [],
        regionOptSelected: [],
      }
    },
    components: {
        
    },
    computed: {
      areaIds() {
        return extractAreaIds(this.regionOptSelected, this.regionOptions);
      }
    },
    filters: {
      cycleListText: function(value) {//任务周期过滤
        return cycleList[value];
      }
    },
    mounted(){
      this.modelId = this.$route.query.id;
      this.type = this.$route.query.type;
      this.regionOptions = getRegion();
      this.regionOptSelected.push(this.regionOptions[0].value,this.regionOptions[0].children[0].value,this.regionOptions[0].children[0].children[0].value);
      if(this.type=="info"){
        document.title = '维保计划模板详情';
        this.disabled=true;
        this.onGetModelDetail();
      }else if(this.type=="update"){
        document.title = '维保计划模板编辑';
        this.disabled=false;
        this.onGetModelDetail();
        this.onGetModelObjList();
      }else if(this.type=="add"){
        document.title = '维保计划模板新增';
        this.disabled=false;
        this.onGetModelObjList();
      }
    },
    methods:{
      lesCycle(){//减少期限组件数值
        if(this.cycle>1)
        return this.cycle--;
      },
      addCycle(){//增加期限组件数值
        return this.cycle++;
      },
      onGetModelDetail:function(){//获取维保计划模板详细信息
        let vm = this;
        getModelDetail(vm.modelId)
        .then(response => {
          vm.detail = response.data;
          vm.regionOptSelected=onSetArea(vm.regionOptions,vm.detail.areaid);
          vm.cycle = vm.detail.expecttime;
          vm.frequency = vm.detail.frequency;
          vm.modelValue = vm.detail.typename;
          vm.cycleVlaue = vm.detail.cycle+"";
          vm.subjectList = vm.detail.subjects;
          vm.name = vm.detail.name;
          vm.id = vm.detail.id;
          vm.note = vm.detail.note;
          vm.on = vm.detail.status;
          console.log("详细信息",vm.detail);
        })
        .catch(error => {
          console.log(error)
        })
      },
      onGetModelObjList(){//获取维保对象类型
        let vm=this;
        const params = {
          type:"",
          page_num: this.page_num,
          page_size: 10000
        }; 
        GetModelObjList(params)
        .then(response => {
          let res = response.data;
          vm.modelOptions = res.rows;
          console.log("模板对象类型",vm.modelOptions)
        }).catch(error => {
          
        })
      },
      handleSelectionChange(val){
        let vm=this;
        vm.subjectsCacheList=val;
        if(vm.type=="update"){//当处于编辑页面时
          for(var i=0; i<vm.subjectsCacheList.length; i++){
            vm.idArr.push(vm.subjectsCacheList[i].id);
          }
        }
      },
      onAddSubject(){//添加缓存执行项
        let vm=this;
        if(!vm.subjectsItem){
          vm.$message.error("执行失败！请将数据填写完整！");
          return;
        }
        if(vm.subjectsItem!=""){
          vm.subjectList.push({"subject_content":this.subjectsItem});
          vm.newEditDialogVisible=false;
          vm.subjectsItem="";
          vm.$message.success("执行成功！");
        }
      },
      onDeleteSubjectItem:function(index,row){//删除一条执行项
        let vm=this;
        vm.$confirm('您确定要删除这条数据吗？', '提示', {//弹出框
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          row.splice(index,1);
          vm.$message.success("执行成功！");
        }).catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消执行'
          });          
        });
      }, 
      onBatchDelete(){//批量删除执行项
        let vm=this;
        if(vm.type=="update"){
          vm.onDeleteSubjectItem_update(0);
        }else{
          vm.$confirm('您确定要删除这些数据吗？', '提示', {//弹出框
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            vm.array_diff(vm.subjectList,vm.subjectsCacheList);
            vm.subjectsCacheList=[];
            vm.$message.success("执行成功！");
          }).catch(() => {
            vm.$message({
              type: 'info',
              message: '已取消执行'
            });          
          });
        }
      },
      array_diff(a, b) {//去除数组重复项  
        for(var i=0;i<b.length;i++){  
          for(var j=0;j<a.length;j++){  
            if(a[j]==b[i]){  
              a.splice(j,1);  
              j=j-1;  
            }  
          }  
        }   
        return a;  
      },
      onAdd(){//新增维保计划模板
        let vm=this;
        const params = {
          "areaid":vm.areaIds,
          "name":vm.name,//模板名称
          "typeid":1,//所属类型
          "targetid":vm.modelValue.split("-")[1],//维保对象类型id
          "typename":vm.modelValue.split("-")[0],//分类名称
          "cycle":vm.cycleVlaue,//周期
          "frequency":vm.frequency,//频率
          "status":vm.on,//模板状态
          "expecttime":vm.cycle,//计划任务周期
          "expect_starttime":"",//预计开始时间（日常巡检）
          "expect_endtime":"",//预计结束时间（日常巡检）
          "creattime":"",//模板创建时间
          "lastrefreshtime":"",//最近执行时间
          "note":vm.note,//备注
          "subjects":vm.subjectList//维保执行项
        };
        createModelManage(params).then(response=>{
          let res=response.data;
          //console.log("新增成功",res.data_id);
          vm.$message.success("执行成功！");
          vm.$router.go(-1);
        }).catch(error =>{
          vm.$message.error("执行失败！");
          console.log("新增失败",error);
        });
        console.log("提交的数据",params)
      },
      onClose(){
        this.$router.go(-1)
      },
      onUpdate(){//修改维保计划模板
        let vm=this;
        const params = {
          "areaid":vm.areaIds,
          "name":vm.name,//模板名称
          "typeid":1,//所属类型
          //"targetid":vm.modelValue,//维保对象类型id
          "typename":vm.modelValue.split("-")[0],//分类名称
          "cycle":vm.cycleVlaue,//周期
          "frequency":vm.frequency,//频率
          "status":vm.on,//模板状态
          "expecttime":vm.cycle,//计划任务周期
          //"expect_starttime":"",//预计开始时间（日常巡检）
          //"expect_endtime":"",//预计结束时间（日常巡检）
          "creattime":"",//模板创建时间
          "lastrefreshtime":"",//最近执行时间
          "note":vm.note,//备注
          //"subjects":vm.subjectList//维保执行项
        };
        updateModelManage(vm.id,params).then(response=>{
          let res=response.data;
          vm.$message.success("修改成功");
          vm.$router.go(-1);
          console.log("修改成功",res.result);
        }).catch(error =>{
          vm.$message.error("修改失败");
          console.log("修改失败",error);
        })
      },
      onAddUpdate(){//添加维保执行项
        let vm=this;
        if(!vm.subjectsItem){
          vm.$message.error("执行失败！请将数据填写完整！");
          return;
        }
        const params = {
          "template_id": vm.id,
          "subject_name": vm.subjectsItem,
          "subject_content": vm.subjectsItem,
          "subject_note": ""
        }
        createExecutionItem(params).then(response => {
          let res=response.data;
          vm.subjectsItem="";
          this.ongetExecutionItemList();
          this.$message.success("执行成功！");//消息提示
          //console.log("添加执行项成功",res.data_id);
        }).catch(error => {
          this.$message.error("执行失败！");
          //console.log("添加执行项失败",error);
        })
        vm.newEditDialogVisible=false;
      },
      ongetExecutionItemList(){//执行项操作完成后(删除，编辑，添加)通过模板id拉取执行项列表
        let vm=this;
        getExecutionItemList(vm.id).then(response => {
          let res=response.data;
          vm.subjectList=res.rows;
          console.log("拉取执行项成功",res.rows);
        }).catch(error => {
          //拉取失败
          console.log("拉取执行项失败",error);
        })
      },
      onDeleteSubjectItem_update(id){//根据执行项id删除维保计划执行项
        let vm=this;
        vm.$confirm('您确定要删除这些数据吗？', '提示', {//弹出框
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if(id!=0){
            vm.idArr.push(id);
          }
          //console.log(vm.idArr);
          const params=vm.idArr;        
          removeExecutionItem(params).then(response => {
            let res=response.data;
            vm.$message.success("执行成功！");
            vm.ongetExecutionItemList();
          }).catch(error => {
            vm.$message.error("执行失败！");
          })
          vm.idArr=[];
        }).catch(() => {
          vm.$message({
            type: 'info',
            message: '已取消执行'
          });          
        });
      },
      onSubjectsItemUpdate(){
        let vm=this;
        if(!vm.editSubjectsItem){
          vm.$message.error("执行失败！请将数据填写完整！");
          return;
        }
        const params={
          "template_id": vm.id,
          "subject_name": vm.editSubjectsItem,
          "subject_content": vm.editSubjectsItem,
          "subject_note": ""
        }
        updateExecutionItem(vm.subject_id,params).then(response => {
          let res=response.data;
          vm.ongetExecutionItemList();
          vm.editDialogVisible=false;
          vm.$message.success("执行项修改成功");
        }).catch(error => {
          vm.$message.error("执行项修改失败");
          console.log("执行项修改失败",error);
        })
      },
      getItem(id){//通过执行项id获取对应执行项详情
        let vm=this;
        getExecutionItem(id).then(response => {
          let res=response.data;
          vm.subject_id=res.id;
          vm.editSubjectsItem=res.subject_name;
          this.editDialogVisible = true;
        }).catch(error => {
          console.log("拉取执行项失败",error);
        });
      },
      updateSubjectList(subItem,l_id){
        let vm=this;
        vm.editDialogVisible=true;
        vm.add_subItem=subItem;
        vm.l_id=l_id;
        vm.editSubjectsItem=subItem;
      },
      onSubjectsItemUpdate_add(){
        let vm=this;
        if(!vm.editSubjectsItem){
          vm.$message.error("执行失败！请将数据填写完整！");
          return
        }
        if(vm.editSubjectsItem!=""){
          vm.subjectList.splice(vm.l_id,1,{"subject_content":vm.editSubjectsItem});
          vm.editDialogVisible=false;
          vm.editSubjectsItem="";
          vm.$message.success("执行成功！");
        }else{
          vm.$message.error("执行失败！请将数据填写完整！");
        }
      }
    }

  }

</script>  



